param(
	#[string]$invoiceRootSiteUrl="$(Read-Host 'Enter the invoice Root web url. [e.g. http://sites/invoices]')",
	[string]$invoiceYear = "$(Read-Host 'Enter the Year for the invoice. [e.g. 2012]')",
	[string]$forceDeleteExistingSite = $TRUE
)



function Update-Scopes($siteUrl)
{
	[void][reflection.assembly]::Loadwithpartialname("Microsoft.SharePoint") | out-null
	[void][reflection.assembly]::Loadwithpartialname("Microsoft.office.server.search") | out-null
	
	$s = [microsoft.sharepoint.spsite]$siteUrl
	$sc = [microsoft.office.server.servercontext]::GetContext($s)
	$search = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($sc)
	$scopes = [microsoft.office.server.search.administration.scopes]$search
	$scopes.StartCompilation()
	while ($scopes.CompilationPercentComplete -lt 100) { sleep -seconds 3; write-host "$($scopes.CompilationPercentComplete)% complete" }
}


#Load variables from configuration file
[System.Xml.XmlDocument] $xmlDoc = New-Object System.Xml.XmlDocument
$file = Resolve-Path (".\deployment.config")

if(!$file){
	Write-Host "Could not find the configuration file deployment.cnofig. Aborting." -ForegroundColor Red
	break
}

Write-Host "Parsing file: " $file
$xmlDoc = [xml](Get-Content $file)

$siteCollectionUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.Url
$invoiceRootSiteUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.InvoiceSite.Url
$searchService = $xmlDoc.Configuration.SearchService.Name
$scopeName =$xmlDoc.Configuration.SearchService.InvoiceSearchScope.Name


if(!$invoiceRootSiteUrl){
	Write-Host "Can't Load Invoice Root Site Url. Aborting." -ForegroundColor Red
	break
}

$invoiceWebTemplateID = "STS#0" #team site
$LOCALE_ID_ENGLISH = 1033
$invoiceListName = "Invoices"
$invoiceListTitle = "Invoices"
$invoiceDocumentName = "InvoiceDocuments" 
$invoiceDocumentTitle = "Invoice Documents" 
$documentTemplateId = 101
$invoiceListTemplateName = "Invoice Definition"

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue


$invoiceWeb = Get-SPWeb -identity $invoiceRootSiteUrl

$siteExist = $invoiceWeb.Webs[$invoiceYear].Exists;



if(($siteExist) -and ($forceDeleteExistingSite -eq $FALSE)){
	$currentSiteUrl = $invoiceWeb.Webs["$invoiceYear"].Url
	Write-Host "This site $currentSiteUrl already exist. Aborting" -ForegroundColor Red
}
else{	
	if(!$invoiceRootSiteUrl.EndsWith("/")){
		$invoiceRootSiteUrl = $invoiceRootSiteUrl + "/"
	}
	
	$webUrl = $invoiceRootSiteUrl + $invoiceYear
	$crawlListUrl = $webUrl + "/Lists/Invoices"
	if($siteExist){
		#delete the site
		Remove-SPWeb -identity $webUrl -Confirm:$false
		Write-Host "Removing site $webUrl..."
		Start-Sleep -Seconds 30
	}
	#good to go, create the site
	#$siteTemplate = $invoiceWeb.GetAvailableWebTemplates($LOCALE_ID_ENGLISH)["$invoiceWebTemplateID"];
	#$invoiceWeb.Webs.Add("$invoiceYear","$invoiceYear","", $LOCALE_ID_ENGLISH,$siteTemplate,"false","false")

	New-SPWeb -Url $webUrl -Template  $invoiceWebTemplateID -Name $invoiceYear
	Write-Host "Creating new site $webUrl..."
	Start-Sleep -Seconds 30
	
	$currentInvoiceWeb = Get-SPWeb -identity $webUrl
	
	#create invoice list
	$invoiceDocumentGuid = $currentInvoiceWeb.Lists.Add($invoiceDocumentName, $invoiceDocumentTitle, 101)
	$invoiceDocument = $currentInvoiceWeb.Lists[$invoiceDocumentGuid]
	if($invoiceDocument){
		Write-Host "Invoice Document Library created successfully." -ForegroundColor Green
	}

	$listTemplate = $invoiceWeb.ListTemplates[$invoiceListTemplateName]; 

	#create invoice documents
	$invoiceListGuid = 	$currentInvoiceWeb.Lists.Add($invoiceListName, $invoiceListTitle, $listTemplate)
	$invoiceList =  $currentInvoiceWeb.Lists[$invoiceListGuid]
	if($invoiceList){
		Write-Host "Invoices List created successfully." -ForegroundColor Green
		$invoiceList.EnableFolderCreation=1
		$invoiceList.Update();
	}
	
	$currentInvoiceWeb.Dispose()
	
	#add crawl rule to the search scope 
	$ssa = Get-SPEnterpriseSearchServiceApplication -Identity $searchService
	$scope = Get-SPEnterpriseSearchQueryScope -Identity $scopeName -SearchApplication $ssa
	$sr = New-SPEnterpriseSearchQueryScopeRule -Scope $scope -RuleType Url -FilterBehavior Include -UrlScopeRuleType Folder -MatchingString $crawlListUrl -Url $invoiceRootSiteUrl
	
	if($sr -ne $null){
		Write-Host "Search Scope Rule for $crawlListUrl is successfully created." -ForegroundColor Green	
	}else{
		Write-Host "Search Scope Rule failed to Created. Manually add search scope rule is required!" -ForegroundColor Red
	}
}

$invoiceWeb.Dispose()

Update-Scopes -siteUrl $siteCollectionUrl

Remove-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue